package com.iflytek.erp.book.service.impl;

import com.iflytek.erp.book.entity.Book;
import com.iflytek.erp.book.entity.BorrowingRecords;
import com.iflytek.erp.book.mapper.BookMapper;
import com.iflytek.erp.book.mapper.BorrowingRecordsMapper;
import com.iflytek.erp.book.service.BookService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

@Service
@Slf4j
public class BookServiceImpl implements BookService {

    @Autowired
    private BookMapper bookMapper;

    @Autowired
    private BorrowingRecordsMapper borrowingRecordsMapper;

    @Override
    public Book getById(Integer id) {
        return bookMapper.findById(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int borrowBook(Integer userId, Integer bookId) {
        Book book = bookMapper.findById(bookId);
        if (1 > book.getInventory()) {
            //2.书籍库存等于0.不可以借阅
            return 0;
        } else {
            //1.校验书籍库存是否大于0
            // 1.1、书籍库存减少.    库存字段=库存字段-1
            book.setInventory(book.getInventory() - 1);
            bookMapper.update(book);
            // 1.2、读者借书后添加借阅记录
            BorrowingRecords br = new BorrowingRecords();
            br.setBookId(bookId);
            br.setBookName(book.getBookName());
            br.setCreateTime(new Date());
            br.setUserId(userId);
            br.setUserName("");//
            borrowingRecordsMapper.insertSelective(br);
            return 1;
        }
    }
}
